package com.hongxun.budget.ui.activity.sg;

import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hongxun.budget.R;
import com.hongxun.budget.ui.activity.BaseActivity;
import com.hongxun.budget.ui.dialog.ListDialog;
import com.hongxun.budget.ui.fragment.sg.EditRecordInfo;
import com.hongxun.budget.utils.RecyclerViewUtils;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.SgDBUtils;
import com.hongxun.budget.utils.SgStrKey;
import com.hongxun.budget.utils.StringUtils;
import com.hongxun.budget.utils.XUtils;
import com.hongxun.entity.ImageUrl;
import com.hongxun.greenentity.tk.DPictureEntity;
import com.hongxun.interfaces.ResponseListener;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;
import com.previewlibrary.GPreviewBuilder;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 新增or编辑项目施工进度记录
 */
public class ScheduleReportAddActivity extends BaseActivity {
    @BindView(R.id.center_title)
    TextView centerTitle;
    @BindView(R.id.right_save)
    Button rightSave;
    @BindView(R.id.tvType1)
    TextView tvType1;
    @BindView(R.id.recyview1)
    RecyclerView recyview1;
    @BindView(R.id.tvType2)
    TextView tvType2;
    @BindView(R.id.recyview2)
    RecyclerView recyview2;

    private EditRecordInfo processDetail;

    private int checkID;
    private String process;
    private SuperAdapter<DPictureEntity> superAdapter1;
    private SuperAdapter<DPictureEntity> superAdapter2;
    private List<DPictureEntity> photos1 = new ArrayList<>();
    private List<DPictureEntity> photos2 = new ArrayList<>();
    private List<String> stringList = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.sg_activity_schedule_report_add;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        //加载本地图片时初始化
        ISNav.getInstance().init(new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });
        rightSave.setVisibility(View.VISIBLE);
        process = String.valueOf(SPUtils.get(context, SgStrKey.namejd, ""));
        centerTitle.setText(String.valueOf(SPUtils.get(context, SgStrKey.namexm, "进度记录")));
        recyview1.addItemDecoration(new DividerItemDecoration(context, LinearLayoutManager.HORIZONTAL));
        recyview1.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForHorizontal(context));
        recyview1.setAdapter(getsuperAdapter1());
        recyview2.addItemDecoration(new DividerItemDecoration(context, LinearLayoutManager.HORIZONTAL));
        recyview2.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForHorizontal(context));
        recyview2.setAdapter(getsuperAdapter2());
        checkedId();
        refreshZp();
    }

    private RecyclerView.Adapter getsuperAdapter2() {
        superAdapter2 = new SuperAdapter<DPictureEntity>(R.layout.content_photo_label) {
            @Override
            public void bindView(ViewHolder viewHolder, final DPictureEntity photos, final int i) {
                ImageView imageView = viewHolder.getView(R.id.imageView);
                ImageButton imageButton = viewHolder.getView(R.id.imageButton);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                XUtils.loadImg(context, SgDBUtils.getUrl(photos), imageView);
                imageButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        photos2.remove(photos);
                        SgDBUtils.delDPictureEntity(photos);
                        notifyDataSetChanged();
                    }
                });
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        List<ImageUrl> urlList = new ArrayList<>();
                        for (DPictureEntity data : photos2) {
                            String url = String.valueOf(SgDBUtils.getUrl(data));
                            urlList.add(new ImageUrl(url, null));
                        }
                        GPreviewBuilder.from(activity)
                                .setData(urlList)
                                .setCurrentIndex(i)
                                .setSingleFling(false)//是否在黑屏区域点击返回
                                .setDrag(false)//是否禁用图片拖拽返回
                                .setType(GPreviewBuilder.IndicatorType.Number)//指示器类型
                                .start();//启动
                    }
                });
            }
        };
        superAdapter2.setData(photos2);
        return superAdapter2;
    }

    private RecyclerView.Adapter getsuperAdapter1() {
        superAdapter1 = new SuperAdapter<DPictureEntity>(R.layout.sg_content_photo_label1) {
            @Override
            public void bindView(ViewHolder viewHolder, final DPictureEntity photos, final int i) {
                ImageView imageView = viewHolder.getView(R.id.imageView);
                ImageButton imageButton = viewHolder.getView(R.id.imageButton);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                XUtils.loadImg(context, SgDBUtils.getUrl(photos), imageView);
                imageButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        photos1.remove(photos);
                        SgDBUtils.delDPictureEntity(photos);
                        notifyDataSetChanged();
                    }
                });
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        List<ImageUrl> urlList = new ArrayList<>();
                        for (DPictureEntity data : photos1) {
                            String url = String.valueOf(SgDBUtils.getUrl(data));
                            urlList.add(new ImageUrl(url, null));
                        }
                        GPreviewBuilder.from(activity)
                                .setData(urlList)
                                .setCurrentIndex(i)
                                .setSingleFling(false)//是否在黑屏区域点击返回
                                .setDrag(false)//是否禁用图片拖拽返回
                                .setType(GPreviewBuilder.IndicatorType.Number)//指示器类型
                                .start();//启动
                    }
                });
            }
        };
        superAdapter1.setData(photos1);
        return superAdapter1;
    }

    //保存
    private void saveData() {
        Observable.just("").subscribeOn(Schedulers.io()).map(new Func1<String, Boolean>() {
            @Override
            public Boolean call(String s) {
                //更新最新进度
                String uuidxm = String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, ""));
                //进度生成或更新最近记录时间
                SgDBUtils.updateCSEntity(context, uuidxm, process);
                //保存填报信息
                processDetail.saveReportEntity();
                //保存照片
                photos2.addAll(photos1);
                for (DPictureEntity entity : photos2) {
                    SgDBUtils.upDataDPictureEntity(entity);
                }
                return true;
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean aBoolean) {
                finish();
            }
        });
    }

    //切换
    private void checkedId() {
        Bundle bundle = new Bundle();
        bundle.putBoolean("isNewAdd", getIntent().getBooleanExtra("isNewAdd", false));
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        processDetail = new EditRecordInfo();
        processDetail.setArguments(bundle);
        transaction.replace(R.id.flayout1, processDetail, "1").commit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            List<String> pathList = new ArrayList<>();
            String resour = "相册";
            if (requestCode == XUtils.CHOISE_IMG) {// 图片选择结果回调
                pathList.addAll(data.getStringArrayListExtra("result"));
            } else if (requestCode == XUtils.CAMERA_IMG) {
                resour = "相机";
                String path = data.getStringExtra("result"); // 图片地址
                pathList.add(path);
            }
            toDPictureEntity(pathList, resour);
        }
    }

    private void toDPictureEntity(List<String> pathList, final String resour) {
        Observable.just(pathList).subscribeOn(Schedulers.io()).map(new Func1<List<String>, Boolean>() {
            @Override
            public Boolean call(List<String> pathList) {
                for (String s : pathList) {
                    DPictureEntity bean = new DPictureEntity();
                    bean.setGuid(StringUtils.getUuid());
                    bean.setPGuid(String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, "")));//所属项目ID
                    bean.setPPGuid(String.valueOf(SPUtils.get(context, SgStrKey.uuidjdjl, "")));//所属进度记录ID
                    bean.setPAppaddress(s);
                    bean.setPStatus("施工");//固定
                    bean.setPDatastate(SgStrKey.add);
                    bean.setPPResour(resour);
                    bean.setPTime(new Date(System.currentTimeMillis()));
                    bean.setPName(s.substring(s.lastIndexOf("/") + 1, s.length()));
                    if (checkID == R.id.ivTakePhoto1) {
                        bean.setPLabel("进度,xc");
                        photos1.add(0, bean);
                    } else if (checkID == R.id.ivTakePhoto2) {
                        bean.setPLabel("进度,zl");
                        photos2.add(0, bean);
                    }
                }
                return true;
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean aBoolean) {
                if (checkID == R.id.ivTakePhoto1) {
                    superAdapter1.notifyDataSetChanged();
                } else if (checkID == R.id.ivTakePhoto2) {
                    superAdapter2.notifyDataSetChanged();
                }
            }
        });
    }

    @OnClick({R.id.right_save, R.id.tvType1,
            R.id.ivTakePhoto1, R.id.tvType2,
            R.id.ivTakePhoto2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.right_save://保存
                saveData();
                break;
            case R.id.tvType1://1类照片类别选择
//                stringList.clear();
//                stringList.add("全部照片");
//                stringList.add("挖坑情况");
//                stringList.add("土质情况");
//                choiceType("选择照片类别");
                break;
            case R.id.ivTakePhoto1://1类照片拍照
//                if (tvType1.getText().toString().trim().equals("全部照片")) {
//                    showMsg("请选择照片类别");
//                    return;
//                }
                checkID = view.getId();
                XUtils.imgClick(activity);
                break;
            case R.id.tvType2://2类照片类别选择
//                stringList.clear();
//                stringList.add("全部照片");
//                stringList.add("设计图纸");
//                stringList.add("现场图纸");
//                choiceType("选择图纸类别");
                break;
            case R.id.ivTakePhoto2://2类照片拍照
//                if (tvType2.getText().toString().trim().equals("全部照片")) {
//                    showMsg("请选择照片类别");
//                    return;
//                }
                checkID = view.getId();
                XUtils.imgClick(activity);
                break;
        }
    }

    private void choiceType(final String title) {
        new ListDialog<String>()
                .setTitle(title)
                .setDatas(stringList)
                .setListener(new ResponseListener() {
                    @Override
                    public void response(Object... data) {
                        if (title.contains("照片类别")) {
                            tvType1.setText(data[0] + "");
                        } else if (title.contains("图纸类别")) {
                            tvType2.setText(data[0] + "");
                        }
                    }
                }).show(getFragmentManager(), title);
    }

    private void refreshZp() {
        final String value1 = String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, ""));
        final String value2 = String.valueOf(SPUtils.get(context, SgStrKey.uuidjdjl, ""));
        Observable.just("进度,xc").subscribeOn(Schedulers.io()).map(new Func1<String, Boolean>() {
            @Override
            public Boolean call(String pLable) {
                photos1.clear();
                photos1.addAll(SgDBUtils.getDPictureList(value1, value2, pLable));
                return true;
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean aBoolean) {
                superAdapter1.notifyDataSetChanged();
            }
        });
        Observable.just("进度,zl").subscribeOn(Schedulers.io()).map(new Func1<String, Boolean>() {
            @Override
            public Boolean call(String pLable) {
                photos2.clear();
                photos2.addAll(SgDBUtils.getDPictureList(value1, value2, pLable));
                return true;
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean aBoolean) {
                superAdapter2.notifyDataSetChanged();
            }
        });
    }
}
